<?php
/**
 * Code.php
 * CopyRight (C) 2019 http://www.xiaomoren.com
 * Author  Showkw <showkw@163.com>
 * Date   2019/10/11 11:05
 */

namespace xmr\response;


use think\response\Json;
use xmr\helper\BaseFunction;

/**
 * Class Code
 *
 * @package xmr\response
 * @author Showkw <showkw@163.com>
 * @date   2019/10/11 11:05
 */
class Code
{
	//通用状态码
	const SUCCESS = [ 0, '操作成功' ];
	const FAIL = [ 1, '操作失败' ];
	const NOT_FOUND_API = [ 2, '未知的API接口' ];
	const EMPTY_DATA = [ 3, '获取数据为空' ];
	const INVALID_PARAMS = [ 4, '非法/无效参数' ];
	const MISS_UPLOAD_FILE = [ 5, '缺少上传文件' ];
	const UPLOAD_FILE_FAIL = [ 6, '上传文件失败' ];
	const NOT_ALLOW_FILE_MIME = [ 7, '文件类型不允许' ];
	const INVALID_REQUESTS_TIMESTAMP = [ 8, '请求时间戳超时/过期' ];
	const REQUEST_FREQUENCY_LIMIT = [ 9, 'API请求频率限制!请稍后再试' ];

	//用户
	const INVALID_PHONE_NUMBER = [ 100, '手机号码不正确' ];
	const USER_PASSWORD_ERROR = [ 101, '用户密码错误' ];
	const PHONE_NUMBER_IS_REGISTERED = [ 102, '该手机号码已注册' ];
	const ERROR_SMS_CODE = [ 103, '短信验证码错误' ];
	const EXPIRED_SMS_CODE = [ 104, '短信验证码已过期' ];
	const ERROR_IMG_CAPTCHA = [ 105, '图形验证码错误' ];
	const EXCEPTION_USER_STATUS = [106,'用户账号状态异常'];
	const NOT_FOUND_USER = [ 107, '用户账号不存在' ];


	/**
	 * 获取状态码对应的错误信息
	 *
	 * @param int $code
	 * @return string
	 * @throws
	 **@author Showkw <showkw@163.com>
	 */
	public static function getCodeMessage( int $code ): string
	{
		$objClass = new \ReflectionClass( __CLASS__ );
		$arrConst = $objClass->getConstants();
		$message = '';
		array_reduce( $arrConst, function ( $res, $v ) use ( $code, &$message ) {
			if ( (int) $v[ 0 ] === $code ) {
				$message = $v[ 1 ];
			}
		} );

		return $message;
	}

	/**
	 * @author Showkw <showkw@163.com>
	 **/
	public static function send( array $code, array $data = null, string $message = null, string $request_id = null )
	{
		$return[ 'request_id' ] = $request_id ?: BaseFunction::getUUID();
		$return[ 'code' ] = $code ? (int) $code[ 0 ] : 0;
		$return[ 'msg' ] = empty( $message ) ? ( $code[1]??Code::getCodeMessage( 0 ) ) : $message;
		$return[ 'data' ] = $codes[ 2 ] ?? ( empty( $data ) ? NULL : $data );
		$return[ 'status' ] = $return[ 'code' ] === 0? 'SUCCESS':'ERROR';
		$return[ 'timestamp' ] = time();

		return Json::create( $return );
	}
}
